package com.kykj.kykj.tool;

/**
 * 七牛云上传工具
 */
import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class KoDoTool {
    @Value("${project.kodoak}")
    private String ak;
    @Value("${project.kodosk}")
    private String sk;
    @Value("${project.kodobucketname}")
    private String bucketName;
    @Value("${project.kodourl}")
    private String bucketUrl;
    @Value("${project.localfilepath}")
    private String localFilePath;

    /**
     * 上传本地文件到七牛云
     * @param filePath 本地文件路径
     * @return 七牛云存储的文件键名
     */
    public String UpLoadFile(String filePath){
        String fileName= UUID.randomUUID().toString()+"."+filePath.split("\\.")[1];
        try{
            Configuration configuration = new Configuration(Region.huadong());//Region.huadong():表示区域在华东
            UploadManager uploadManager = new UploadManager(configuration);
            Auth auth = Auth.create(ak,sk);//根据Key和Secret获取Token
            String token = auth.uploadToken(bucketName);
            Response response = uploadManager.put(filePath,fileName,token);//获取上传请求头
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);//上传文件并返回结果
            System.out.println(bucketUrl+"/"+fileName);
            return bucketUrl+"/"+fileName;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

}